package lab3;

import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DigestInterface
implements Runnable
{
	private String [] files;
	private static DigestInterface instance = null;
	private Thread[] threads;
	private ExecutorService threadPool = null;
	//singleton class fits really well here
	
	private DigestInterface()
	{
		//nothing to do here.
	}
		
	public void setFiles (String [] paths)	
	{
		this.files = paths;
		this.threads = new Thread [paths.length];
	}
	
	public void setFiles (String [] paths, int poolSize)
	{
		this.files = paths;
		this.threadPool = Executors.newFixedThreadPool(this.files.length);
	}
		
	public static DigestInterface getInstance ()
	{
		if (DigestInterface.instance == null)
		{
			//create a new instance
			DigestInterface.instance = new DigestInterface();
		}
		else 
		{
			//instance has already been created
		}
		
		return DigestInterface.instance;
	}
		
 	synchronized void printDigestOutput (byte[] arr, String path)
	{
		System.out.print(path);
		System.out.print(": ");
		
		for(int i = 0; i < arr.length; i++)
		{
			System.out.print((int)arr[i]);
			System.out.print(" ");
		}
		System.out.print("\n");
	}
 	 	
 	private void lab3(File f, int threadIndex) throws InterruptedException
 	{
		DigestWorker dw = new DigestWorker(this, f);
		Thread t = new Thread (dw);
		this.threads[threadIndex] = t;
		t.join();
		t.start();
 	}
 	
 	private void lab4 (File f)
 	{
 		this.threadPool.execute(new DigestWorker(this, f));
 	}

	@Override
	public void run()
	{
		for (int i = 0; i < this.files.length; i++)
		{
			try
			{
				File f = new File (this.files[i]);
				
				if(f.exists())
				{
					if(threadPool == null)
					{
						this.lab3(f, i);
					}
					else
					{
						this.lab4(f);
					}
				}
				else
				{
					System.out.println("File: " +this.files[i]+" does not exist");;
				}
			} 
			catch (InterruptedException e)
			{
				System.out.println("Thread start failed.");
				
			}
		}
		this.threadPool.shutdown();
	}
}
